import { View, Switch } from '@tarojs/components'
import { useLoad } from '@tarojs/taro';
import { useEffect, useState } from 'react';
import { WarningOutlined } from '@taroify/icons';
import utils from '@/utils';
import { formContextProvider } from '../BtForm/formContextProvider';
import './index.scss'

interface BtFormItemProps {
  label: string;
  children: React.ReactNode;
  prop?: string;
  enable?: boolean;
  onChange?: (value) => void;
  iconRemark?: string;
  haveUnderline?: boolean;
}

export default function BtFormItem ( {label, enable, onChange, iconRemark, children, prop, haveUnderline = true}: BtFormItemProps) {
  const [ errMsg, setErrMsg ] = useState('')
  const [ isRequired, setIsRequired ] = useState(false)
  const [state, dispatch] = formContextProvider.useTracked()

  useEffect(() => {
    if (prop) {
      const rule = state.rules[prop]

      if (rule) {
        rule.forEach((item: any) => {
          if(item.required){
            setIsRequired(true)
          }
        })
      }
    }
  }, [state.rules, prop])

  useEffect(() => {
    if (prop) {
      dispatch({ type: "addField", field: {
        prop,
        setErrMsg
      }})
    }
  }, [prop, dispatch])

  const handleShowIconRemark = () => {
    if (iconRemark) {
      utils.$toast(iconRemark)
    }
  }

  return (
    <View className='form-item'>
      <View className='at-row'>
        <View className='label flex justify-between items-center'
          style={{ marginBottom: (enable !== undefined && onChange) ? '8rpx' : '12rpx' }}
        >
          <View className='flex items-center'>
            <View className='label-text'>{label}</View>
            <View className='required'>{isRequired ? '*' : ''}</View>
            { iconRemark && <WarningOutlined className='icon-remark' onClick={handleShowIconRemark} /> }
          </View>
          {
            (enable !== undefined && onChange) && (
              <Switch
                className='switch'
                color='#4575C9'
                checked={enable}
                onChange={(e) => { onChange({detail: {value: e.detail.value}}) }}
              />
            )
          }
        </View>
        <View className='content'>{children}</View>
      </View>
      {
        errMsg && <View className='errMsg'>{errMsg}</View>
      }
      <View className={`${haveUnderline ? 'under-line': 'line'}`}></View>
    </View>
  )
}
